package com.nsoft.html5npub.utils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.ImageButton;

public class ExImageButton extends ImageButton {
	public static int OPACITY_ENABLE=255;
	public static int OPACITY_DISABLE=100;
	
	private Drawable d;
	
	public ExImageButton(Context context) {
		super(context);
	}

	public ExImageButton(Context context,
						AttributeSet attrs) {
		super(context, attrs);
	}

	public ExImageButton(Context context, 
						AttributeSet attrs, 
						int defStyle) {
		super(context, attrs, defStyle);
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public void setEnabled(boolean enabled){
		if (d!=null){
			d.mutate();
			setAlpha(enabled?
					OPACITY_ENABLE:
					OPACITY_DISABLE);
			d.invalidateSelf();
		}
		super.setEnabled(enabled);
	}
	
	@Override
	public void setImageDrawable(Drawable drawable) {
		this.d=drawable;
		/*
		CustomBackgroundDrawable layer=
				new CustomBackgroundDrawable(drawable);
		*/
		super.setImageDrawable(drawable);
	}
	
	/**
	 * this class handles the state background image of the
	 * button (normal, pressed and disable).
	 * 
	 * @author minhld
	 *
	 */
	protected class CustomBackgroundDrawable extends LayerDrawable{

		protected ColorFilter _pressedFilter=
				new LightingColorFilter(Color.LTGRAY, 1);
		protected int _disabledAlpha=150;

		public CustomBackgroundDrawable(Drawable d) {
			super(new Drawable[] { d });
		}

		@Override
		protected boolean onStateChange(int[] states) {
			boolean enabled = false;
			boolean pressed = false;

			for (int state:states) {
				if (state==android.R.attr.state_enabled)
					enabled=true;
				else if (state==android.R.attr.state_pressed)
					pressed=true;
			}

			mutate();
			if (enabled&&pressed) {
				setColorFilter(_pressedFilter);
			} else if (!enabled) {
				setColorFilter(null);
				setAlpha(_disabledAlpha);
			} else {
				setColorFilter(null);
			}

			invalidateSelf();
			return super.onStateChange(states);
		}

		@Override
		public boolean isStateful() {
			return true;
		}
	}
	
}
